<template>
  <el-dialog
    :model-value="dialogVisible"
    :title="isEdit ? '编辑分类' : '新增分类'"
    width="500px"
    :before-close="handleClose"
    @update:model-value="dialogVisible = $event"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item v-if="parentCategory" label="父分类">
        <el-input :value="parentCategory.name" disabled />
      </el-form-item>
      
      <el-form-item label="分类名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入分类名称"
        />
      </el-form-item>
      
      <el-form-item label="分类编码" prop="code">
        <el-input
          v-model="formData.code"
          placeholder="请输入分类编码"
        />
      </el-form-item>
      
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入分类描述"
        />
      </el-form-item>
      
      <el-form-item label="排序" prop="sort">
        <el-input-number
          v-model="formData.sort"
          :min="0"
          :max="999"
          placeholder="排序"
        />
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

interface Category {
  id: number
  name: string
  code: string
  description?: string
  parentId?: number
  sort: number
  status: number
  createTime: string
}

interface Props {
  visible: boolean
  categoryData?: Category | null
  isEdit: boolean
  parentCategory?: Category | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success', category: Category): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 表单引用
const formRef = ref<FormInstance>()
const loading = ref(false)

// 表单数据
const formData = reactive<Partial<Category>>({
  name: '',
  code: '',
  description: '',
  sort: 0,
  status: 1
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '分类名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入分类编码', trigger: 'blur' },
    { min: 2, max: 20, message: '分类编码长度在 2 到 20 个字符', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '分类编码只能包含大写字母和下划线', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述长度不能超过 200 个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 监听分类数据变化
watch(
  () => props.categoryData,
  (newData) => {
    if (newData) {
      Object.assign(formData, {
        name: newData.name,
        code: newData.code,
        description: newData.description,
        sort: newData.sort,
        status: newData.status
      })
    } else {
      resetForm()
    }
  },
  { immediate: true }
)

// 监听对话框显示状态
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      if (!props.categoryData) {
        resetForm()
      }
    }
  }
)

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    code: '',
    description: '',
    sort: 0,
    status: 1
  })
  formRef.value?.clearValidate()
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    const categoryData: Category = {
      id: props.categoryData?.id || 0,
      name: formData.name!,
      code: formData.code!,
      description: formData.description || '',
      parentId: props.parentCategory?.id,
      sort: formData.sort!,
      status: formData.status!,
      createTime: props.categoryData?.createTime || new Date().toLocaleString()
    }
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    if (props.isEdit) {
      ElMessage.success('分类更新成功')
    } else {
      ElMessage.success('分类创建成功')
    }
    
    emit('success', categoryData)
  } catch (error) {
    console.error('表单提交失败:', error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped lang="scss">
.dialog-footer {
  text-align: right;
}
</style>

